// httpService.js
import axios from 'axios';

const API_URL = 'http://localhost:8082'; // 使用HTTPS

class HttpService {
    constructor() {
        this.instance = axios.create({
            baseURL: API_URL,
            timeout: 10000, // 设置超时时间
            headers: {
                'Content-Type': 'application/json',
            },
        });

        // 添加请求拦截器
        this.instance.interceptors.request.use(
            config => {
                // 在发送请求之前添加 token
                // const token = this.getToken();
                // if (token) {
                //     config.headers['Authorization'] = `Bearer ${token}`;
                // }
                console.log('Request:', config);
                return config;
            },
            error => {
                // 对请求错误做些什么
                console.error('Request error:', error);
                return Promise.reject(error);
            }
        );

        // 添加响应拦截器
        this.instance.interceptors.response.use(
            response => {
                // 对响应数据做些什么
                console.log('Response:', response);
                return response;
            },
            error => {
                // 对响应错误做些什么
                console.error('Response error:', error);
                return Promise.reject(error);
            }
        );
    }

    setToken(token) {
        localStorage.setItem('token', token);
    }

    getToken() {
        return localStorage.getItem('token');
    }

    async get(url, params = {}) {
        try {
            const response = await this.instance.get(url, { params });
            return response.data;
        } catch (error) {
            console.error('GET request failed:', error);
            throw error;
        }
    }

    async post(url, data = {}) {
        try {
            const response = await this.instance.post(url, data);
            return response.data;
        } catch (error) {
            console.error('POST request failed:', error);
            throw error;
        }
    }

    async put(url, data = {}) {
        try {
            const response = await this.instance.put(url, data);
            return response.data;
        } catch (error) {
            console.error('PUT request failed:', error);
            throw error;
        }
    }

    async delete(url, params = {}) {
        try {
            const response = await this.instance.delete(url, { params });
            return response.data;
        } catch (error) {
            console.error('DELETE request failed:', error);
            throw error;
        }
    }
}

const httpService = new HttpService();
export default httpService;
